package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WXPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/wxpay")
@RestController
public class WXPayController {
    @Autowired
    private WXPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //下单
    @GetMapping("nativePay")
    public Result nativePay(@RequestParam("orderId") String orderId, @RequestParam("money") Integer money) {
        Map resultMap = wxPayService.nativePay(orderId, money);
        return new Result(true, StatusCode.OK, "", resultMap);
    }

    @RequestMapping("/notify")
    public void notifyLogin(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("支付成功回调");
        try {
            //输入流转换为一个字符串
            String xml = ConvertUtils.convertToString(request.getInputStream());
            System.out.println(xml);

            //基于微信发送的通知消息，完成后续业务的逻辑处理
            Map<String, String> map = WXPayUtil.xmlToMap(xml);//将微信返回来的通知消息转换为map对象
            if ("SUCCESS".equals(map.get("result_code"))) { //判断微信发送通知是否成功
                //查询订单信息
                Map result = wxPayService.queeyOrder(map.get("out_trade_no"));
                System.out.println("查询订单结果:" + result);
                if ("SUCCESS".equals(result.get("trade_state"))) {//判断微信通知中是否支付成功
                    //如果成功支付,则将支付成功后的订单消息发送到mp
                    Map message = new HashMap();
                    message.put("orderId", result.get("out_trade_no"));//添加我们本地生成的订单id
                    message.put("transactionId", result.get("transaction_id"));//添加微信生成的流水号

                    //发送消息到MQ
                    rabbitTemplate.convertAndSend("", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(message));
                } else {
                    //输出错误原因
                    System.out.println(map.get("err_code_des"));
                }
            } else {
                //输出错误原因
                System.out.println(map.get("err_code_des"));
            }
        } catch (Exception e) {
            //打印错误信息
            e.printStackTrace();
        }
    }
}
